package com.bbmall;

import org.apache.spark.sql.SparkSession;
public class SparkSessionUtil {
    private static volatile SparkSession sparkSession;

    // 私有构造方法防止实例化
    private SparkSessionUtil() {}

    /**
     * 获取SparkSession实例（单例模式）
     * @param appName 应用名称
     * @return SparkSession
     */
    public static SparkSession getSparkSession(String appName) {
        if (sparkSession == null) {
            synchronized (SparkSessionUtil.class) {
                if (sparkSession == null) {
                    sparkSession = SparkSession.builder()
                            .appName(appName)
                            .enableHiveSupport()
                            .config("spark.sql.sources.partitionOverwriteMode", "dynamic") // 动态分区覆盖
                            .config("spark.sql.shuffle.partitions", "200") // 调整shuffle分区数
                            .getOrCreate();
                }
            }
        }
        return sparkSession;
    }

    /**
     * 关闭SparkSession
     */
    public static void close() {
        if (sparkSession != null) {
            sparkSession.stop();
            sparkSession = null;
        }
    }
}
